package org.springblade.test.csv;

import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;

public class CSVUtil {
	public static char separator = ',';

	public static void main(String[] args) throws Exception {
		// 测试导出
		String filePath = "E:\\logs\\2020-01-08.csv";
		/*List<String[]> dataList = new ArrayList<String[]>();
		//添加标题
		dataList.add(new String[]{"学号", "姓名", "分数"});
		for (int i = 0; i < 10; i++) {
			dataList.add(new String[]{"2010000" + i, "张三" + i, "8" + i});
		}
		createCSV(dataList, filePath);*/

		// 读取CSV文件
		Map<String,Object> csvMap=readCSV(filePath);
		List<String> headList= (List<String>) csvMap.get("head");
		List<Map<String,String>> dataList= (List<Map<String, String>>) csvMap.get("dataList");
		for(Map<String,String> data:dataList){
			System.out.println(data.get("order_book_id"));
			System.out.println(data.get("symbol"));
		}
	}

	/**
	 * 读取CSV文件
	 * @param filePath:全路径名
	 */
	public static Map<String,Object> readCSV(String filePath) throws Exception {
		CsvReader reader = null;
		Map<String,Object> csvMap=new HashMap<>();
		try {
			//如果生产文件乱码，windows下用gbk，linux用UTF-8
			reader = new CsvReader(filePath, separator, Charset.forName("UTF-8"));

			// 读取表头
			reader.readHeaders();
			String[] headArray = reader.getHeaders();//获取标题
			List<String> headList=Arrays.asList(headArray);
			csvMap.put("head", headList);
			List<Map<String,String>> dataList=new ArrayList<Map<String,String>>();
			csvMap.put("dataList", dataList);
			System.out.println(csvMap.get("head"));

			// 逐条读取记录，直至读完
			while (reader.readRecord()) {
				// 读一整行
				System.out.println(reader.getRawRecord());
				Map<String,String> data=new HashMap<>();
				for(int i=0;i<headList.size();i++){
					String head=headList.get(i);
					data.put(head,reader.get(head));
				}
				dataList.add(data);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != reader) {
				reader.close();
			}
		}

		return csvMap;
	}

	/**
	 * 生成CSV文件
	 * @param dataList:数据集
	 * @param filePath:全路径名
	 */
	public static boolean createCSV(List<String[]> dataList, String filePath) throws Exception {
		boolean isSuccess = false;
		CsvWriter writer = null;
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(filePath, true);
			//如果生产文件乱码，windows下用gbk，linux用UTF-8
			writer = new CsvWriter(out, separator, Charset.forName("GBK"));
			for (String[] strs : dataList) {
				writer.writeRecord(strs);
			}
			isSuccess = true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != writer) {
				writer.close();
			}
			if (null != out) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return isSuccess;
	}
}
